<?php


namespace app\controller;


use app\model\Images;
use app\model\Questions;
use app\validate\Image;
use think\facade\Session;
use think\Request;

class Question extends Base
{
    public function create(Request $request){
        $data=$request->param();
        $files = request()->file('image');
        $username=Session::get('username');
        if($data['q_content']==null){
            return $this->createApi([],'问题不能为空',204);
        }
        $is_friend=$data['is_friend']?$data['is_friend']:0;
        $is_school=$data['is_school']?$data['is_school']:0;
        $question=Questions::create([
            'q_user'=>$username,
            'q_content'=>$data['q_content'],
            'reward'=>$data['reward'],
            'is_friend'=>$is_friend,
            'is_school'=>$is_school
        ])->toArray();
        $q_id=$question['id'];
                if($files){
                    try {
                        validate(Image::class)
                            ->check($files);
                        $savename = [];
                        foreach($files as $file) {
                            $save = \think\facade\Filesystem::disk('public')->putFile('questions', $file);
                            $image = Images::create([
                                'is_ques' => 1,
                                'q_id' => $q_id,
                                'img_add' => 'storage/' . str_replace('\\', '/', $save)
                            ]);
                            $savename[] = $save;
                        }
                            $question['images']=$savename;
                    } catch (\think\exception\ValidateException $e) {
                        return $this->createApi([],$e->getMessage(),400);
                    }
                }
        return $this->createApi($question,'success',200);
    }
    public function read(Request $request){
        $data=$request->param();
        if(isset($data['questionid'])&&$data['questionid']!=0){
                $ques=Questions::where('q_id',$data['questionid'])->field('q_user,q_content')->select()->toArray();
                $images=Images::where('q_id',$data['questionid'])->field('img_add')->select()->toArray();
                $ques['images']=$images;
                if($ques){
                    return $this->createApi($ques,'查看问题成功',200);
                }else{
                    return $this->createApi([],'查看问题失败',204);
                }
        }
    }
}